package com.wn.budget.controller;

import com.wn.budget.code.VerifyCodeUtils;
import com.wn.budget.code.context.ContextManager;
import com.wn.budget.model.Admin;
import com.wn.budget.repository.AdminRepository;
import com.wn.budget.service.admin.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(value = "管理员管理")
@RestController
@RequestMapping("admin")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminRepository adminRepository;

    @ApiOperation(value = "登录")
    @GetMapping("login")
    public Admin login(HttpServletRequest request, @RequestParam("account") String account,
            @RequestParam("password") String password, @RequestParam("code") String code) {
        Object verifyCode = request.getSession().getAttribute("CODE");
        if(verifyCode==null){
            throw new RuntimeException("验证码为空。");
        }
        if (!verifyCode.toString().toLowerCase().equals(code.toLowerCase())) {
            throw new RuntimeException("验证码不正确。");
        }
        return adminService.login(request, account, password);
    }

    @ApiOperation(value = "退出登录")
    @GetMapping("logout")
    public boolean logout(HttpServletRequest request) {
        return adminService.logout(request);
    }

    @ApiOperation(value = "修改密码")
    @GetMapping("updatePassword")
    public boolean updatePassword(HttpServletRequest request, @RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword) {

        Admin admin = ContextManager.getLoginUser(request);
        if(!admin.getPassword().equals(oldPassword)){
            throw new RuntimeException("旧密码输入错误");
        }
        admin.setPassword(newPassword);
        adminRepository.saveAndFlush(admin);
        return true;
    }

    /**
     * 获取验证码
     *
     * @param width  高
     * @param height 宽
     */
    @ApiOperation(value = "获取验证码")
    @GetMapping("getVerifyCode")
    public void getVerifyCode(HttpServletRequest req, HttpServletResponse resp, @RequestParam("width") int width,
            @RequestParam("height") int height) throws IOException {
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/jpeg");

        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 存入会话session
        req.getSession().setAttribute("CODE", verifyCode.toLowerCase());

        // 生成图片
        VerifyCodeUtils.outputImage(width, height, resp.getOutputStream(), verifyCode);
    }
}
